package com.mlethe.android.demo;

import android.content.Context;
import android.util.Log;

import com.mlethe.library.utils.file.FileUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Author: Patter
 * Data:  2019/3/26
 * Email: 401219741@qq.com
 * 全局异常捕获
 */
public class KqwException implements Thread.UncaughtExceptionHandler {
    private static KqwException myCrashHandler;


    private KqwException() {
    }

    public static synchronized KqwException getInstance() {
        if (null == myCrashHandler) {
            myCrashHandler = new KqwException();
        }
        return myCrashHandler;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        long threadId = thread.getId();
        String message = throwable.getMessage();
        String localizedMessage = throwable.getLocalizedMessage();
        Log.i("KqwException", "------------------------------------------------------");
        Log.i("KqwException", "threadId = " + threadId);
        Log.i("KqwException", "message = " + message);
        Log.i("KqwException", "localizedMessage = " + localizedMessage);
        Log.i("KqwException", "------------------------------------------------------");
        throwable.printStackTrace();
        Log.i("KqwException", "------------------------------------------------------");
        // TODO 下面捕获到异常以后要做的事情，可以重启应用，获取手机信息上传到服务器等
        Log.i("KqwException", "------------------应用被重启----------------");

        try {
            final SimpleDateFormat dateFormat = new SimpleDateFormat("'log'_yyyyMMdd_HH", Locale.getDefault());
            String dirPath = FileUtil.getCacheDirectory() + "/SkyLine/breakdown/logs/";
            File file = FileUtil.createFile(dirPath, dateFormat.format(new Date()) + ".txt");
            final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
            String stackTraceInfo = sdf.format(new Date()) + " /com.enovatemotors.newretail E/ ";
            stackTraceInfo += getStackTraceInfo(throwable);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(stackTraceInfo.getBytes());
            FileUtil.write(inputStream, file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 重启应用
//        mContext.startActivity(mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName()));
        //干掉当前的程序
//        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 获取错误的信息
     *
     * @param throwable
     * @return
     */
    private String getStackTraceInfo(final Throwable throwable) {
        PrintWriter pw = null;
        Writer writer = new StringWriter();
        try {
            pw = new PrintWriter(writer);
            throwable.printStackTrace(pw);
        } catch (Exception e) {
            return "";
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
        return writer.toString();
    }

}
